package com.hc.comm.base;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hc.comm.utils.MyLog;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public abstract class BaseController {

    protected Logger logger = Logger.getLogger(this.getClass());

    protected HttpServletRequest request;

    protected HttpServletResponse response;

    /**
     * @param request
     * @param response
     * @Title: setReqAndResp
     * @Description: 初始化ServletAPI
     */
    @ModelAttribute
    public void setReqAndResp(HttpServletRequest request,
                              HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    protected void writeToJson(Object object, ContentTypeEnum contentTypeEnum)
            throws IOException {
        writeToJson(object, null, contentTypeEnum);
    }

    protected void writeToJson(Object object, SerializeFilter filter)
            throws IOException {
        writeToJson(object, filter, ContentTypeEnum.TEXT_JSON);
    }

    protected void writeToJson(Object object)
            throws IOException {
        writeToJson(object, null, ContentTypeEnum.TEXT_JSON);
    }

    protected void writeToJson(Object object, SerializeFilter filter, ContentTypeEnum contentTypeEnum)
            throws IOException {
        response.setContentType(contentTypeEnum.getValue());
        //{"s1":{"age":16,"name":"s1"},"s2":{"$ref":"$.s1"}} 禁止循环引用
        SerializerFeature feature = SerializerFeature.DisableCircularReferenceDetect;
        String jsonString = JSONObject.toJSONString(object, filter, feature);
        MyLog.log(jsonString);
        PrintWriter writer = response.getWriter();
        try {
            writer.write(jsonString);
        } finally {
            writer.flush();
            writer.close();
        }
    }

    /**
     * 内容类型
     */
    public enum ContentTypeEnum {
        TEXT_HTML("text/html; charset=UTF-8"), TEXT_PLAIN(
                "text/plain; charset=UTF-8"), TEXT_JSON(
                "text/json; charset=UTF-8");
        String value;

        ContentTypeEnum(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }


    public void outSuccessData() {

    }

    public void outFailData() {

    }
}
